package top.jle.spring.basic.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.text.RandomStringGenerator;

import java.util.Optional;

import static org.apache.commons.text.CharacterPredicates.DIGITS;
import static org.apache.commons.text.CharacterPredicates.LETTERS;

/**
 * 使用RandomStringGenerator实现随机字符生成
 * @description 替代 {@link org.apache.commons.lang3.RandomStringUtils} RandomStringUtils使用Random实现随机算法 有安全隐患
 * @date  2023/7/17 上午9:40
 * @author  jim.lee
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RandomStringUtil {

    @RequiredArgsConstructor
    public enum GeneratePolicy{

        /**
         * 生成英文字母(包含大小写)和数字
         */
        LETTER_AND_DIGIT(new RandomStringGenerator.Builder().withinRange(new char[]{'0','9'},new char[]{'a','z'},new char[]{'A','Z'}).filteredBy(LETTERS,DIGITS).build()),
        /**
         * 生成英文字母(大写)和数字
         */
        UPPER_LETTER_AND_DIGIT(new RandomStringGenerator.Builder().withinRange(new char[]{'0','9'},new char[]{'A','Z'}).filteredBy(LETTERS,DIGITS).build()),
        /**
         * 生成英文字母(大写)和数字
         */
        LOWER_LETTER_AND_DIGIT(new RandomStringGenerator.Builder().withinRange(new char[]{'0','9'},new char[]{'a','z'}).build()),
        /**
         * 生成英文字母 (包含大小写)
         */
        LETTER(new RandomStringGenerator.Builder().withinRange(new char[]{'a','z'},new char[]{'A','Z'}).build()),
        /**
         * 生成英文字母 (大写)
         */
        LOWER_LETTER(new RandomStringGenerator.Builder().withinRange(new char[]{'a','z'}).build()),
        /**
         * 生成英文字母 (小写)
         */
        UPPER_LETTER(new RandomStringGenerator.Builder().withinRange(new char[]{'A','Z'}).build()),
        /**
         * 生成数字
         */
        DIGIT(new RandomStringGenerator.Builder().withinRange(new char[]{'0','9'}).build()),
        ;

        private final RandomStringGenerator generator;
        private String generate(int length){
            return this.generator.generate(length);
        }
    }



    public static String randomString(int length,GeneratePolicy generatePolicy){

        return Optional.ofNullable(generatePolicy).orElse(GeneratePolicy.LETTER_AND_DIGIT).generate(Math.max(length,1));
       
    }

    public static void main(String[] args) {
        Object[] values = new Object[0];
        System.out.println(ObjectUtils.anyNull(values));
    }

}
